package uiao.step3_connection_holder;

import uiao.BankService;

import javax.sql.DataSource;

public class ConnectionHolderBankService implements BankService {
    private TransactionManager transactionManager;
    private ConnectionHolderBankDao connectionHolderBankDao;
    private ConnectionHolderInsuranceDao connectionHolderInsuranceDao;

    public ConnectionHolderBankService(DataSource dataSource) {
        transactionManager = new TransactionManager(dataSource);
        connectionHolderBankDao = new ConnectionHolderBankDao(dataSource);
        connectionHolderInsuranceDao = new ConnectionHolderInsuranceDao(dataSource);

    }

    @Override
    public void transfer(int fromId, int toId, int amount) {
        try {
            // 执行以下三个方法的是一个线程，所以获取的ConnectionHolder也是一个
            // 每个方法内部都会先调用SingleThreadConnectionHolder类的getConnection方法获取ConnectionHolder
            transactionManager.start();
            connectionHolderBankDao.withdraw(fromId, amount);
            connectionHolderInsuranceDao.deposit(toId, amount);
            transactionManager.commit();
        } catch (Throwable e) {
            System.out.println("回滚");
            transactionManager.rollback();
        } finally {
            transactionManager.close();
        }
    }
}
